package tk.ovzs.starcraftRanker;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import tk.ovzs.DataModels.UserProfile;
import tk.ovzs.PageScraper.WebPageScraper;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;

public class StarcraftRankerConfigurator extends Activity implements OnClickListener
{
	private int mAppWidgetId;

	private Button okButton;
	private TextView testTextView;
	private EditText urlTextBox;

	private Document docum;
	private UserProfile userProfile;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.starcraft_configurator_layout);
		Log.d("misc", "onCreateConfigurator");

		okButton = (Button) findViewById(R.id.okButton);
		testTextView = (TextView) findViewById(R.id.textView1);
		urlTextBox = (EditText) findViewById(R.id.urlTextBox);

		okButton.setOnClickListener(this);

		//		Intent intent = getIntent();
		//		Bundle extras = intent.getExtras();
		//		if (extras != null) {
		//		    mAppWidgetId = extras.getInt(
		//		            AppWidgetManager.EXTRA_APPWIDGET_ID, 
		//		            AppWidgetManager.INVALID_APPWIDGET_ID);
		//		}
		//		

		//		
		//		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		//		
		//		
		//		RemoteViews views = new RemoteViews(context.getPackageName(),
		//				R.layout.starcraft_ranker_layout);
		//				appWidgetManager.updateAppWidget(mAppWidgetId, views);
	}
	
	private Handler messageHandler = new Handler()
	{

		public void handleMessage(Message msg) 
		{			
			Log.d("misc", "received message: " + msg);

			if (msg.what == 0)
			{
				WebPageScraper.parseDocument(docum);
				UserProfile.getInstance().setUserProfileURL(urlTextBox.getText().toString());
				userProfile = UserProfile.getInstance();
				showWidget();
			}
			super.handleMessage(msg);	
		}
	};
	
	public void showWidget ()
	{
		userProfile = UserProfile.getInstance();
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null)
		{
			mAppWidgetId = extras.getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID, 
					AppWidgetManager.INVALID_APPWIDGET_ID);

			Context context = getApplication();
//
			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

			RemoteViews views = new RemoteViews(this.getPackageName(),
					R.layout.starcraft_ranker_layout);
			views.setTextViewText(R.id.playerName, "User: " + userProfile.getUserName());
			views.setTextViewText(R.id.playerLeague, "League: " + userProfile.getUserDivision1().toString());
			views.setTextViewText(R.id.playerRank, "Rank: " + String.valueOf(userProfile.getUserRank1()));
            views.setTextViewText(R.id.lastUpdate, new SimpleDateFormat().format(new Date()));
            
            Intent configIntent = new Intent(context, StarcraftRankerConfigurator.class);
            configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            configIntent.setAction(StarcraftRankerProvider.ACTION_WIDGET_CONTROL);
            
            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
            views.setOnClickPendingIntent(R.id.configureButton, configPendingIntent);	
			//	            views.setOnClickPendingIntent(R.id.refreshButton, pendingIntent);
			appWidgetManager.updateAppWidget(mAppWidgetId, views);

			Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_OK, resultValue);
			
            Intent widgetUpdate = new Intent();
            widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { mAppWidgetId });

            // make this pending intent unique
//            widgetUpdate.setData(Uri.withAppendedPath(Uri.parse(ImagesWidgetProvider.URI_SCHEME + "://widget/id/"), String.valueOf(appWidgetId)));
            PendingIntent newPending = PendingIntent.getBroadcast(getApplicationContext(), 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);

            // schedule the new widget for updating
            AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 50 * 1000, newPending);
            
			finish();
		}
	}

	@Override
	public void onClick(View v)
	{
		if(v ==okButton)
		{
			//			WebPageScraper wps = new WebPageScraper("http://us.battle.net/sc2/en/profile/909938/1/Ewal/");
			//			wps.pageRequest();
			//			String xml = wps.getXmlFromUrl("http://eu.battle.net/sc2/en/profile/1475162/1/Sheldor/");			
			//			Document xmlDocument = wps.getDomElement(xml);
			//			URI uri = new URI("http://eu.battle.net/sc2/en/profile/1475162/1/Sheldor/");

			String urlString = urlTextBox.getText().toString();

			if ((urlString.startsWith("http://") || urlString.startsWith("www."))  && urlString.contains("battle.net"))
			{
//				showWidget();
				docum = null;
				//					docum = (Document) Jsoup.parse(url, 9000);
				new Thread() {			
					
					public void run() {
						try 
						{							
							URL url = new URL(urlTextBox.getText().toString());
							docum = (Document) Jsoup.parse(url, 9000);
							if (docum != null)
							{
								messageHandler.sendEmptyMessage(0);
							}
							else
							{
								messageHandler.sendEmptyMessage(1);
							}
						}
						catch (IOException e)
						{
							messageHandler.sendEmptyMessage(1);
						}
					}
				}.start();
				
				//docum = Jsoup.parse(input, "UTF-8", "http://example.com/");						
			}
			else // link not valid
			{
				AlertDialog.Builder builder = new AlertDialog.Builder(StarcraftRankerConfigurator.this);			
				builder.setTitle("Error!");
				builder.setMessage("URL seems to be invalid");
				builder.setCancelable(true);
				AlertDialog dialog = builder.create();
				dialog.show();
			}
		}	// <-- ok Button ends here
	}
}